package servlet;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.GroupLayout.Alignment;
import javax.xml.ws.Response;

import manager.Manager;

import com.itextpdf.text.Anchor;
import com.itextpdf.text.BadElementException;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chapter;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.List;
import com.itextpdf.text.ListItem;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Section;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

import data.Medecin;
import data.Medicament;
import data.Ordonnance;
import data.Patient;

/**
 * Servlet implementation class TestServletImg
 */
public class PDFOrdonnance extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
    
	Manager manager;
	
	private static Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18,
			Font.BOLD);
	private static Font redFont = new Font(Font.FontFamily.TIMES_ROMAN, 12,
			Font.NORMAL, BaseColor.RED);
	private static Font subFont = new Font(Font.FontFamily.TIMES_ROMAN, 16,
			Font.BOLD);
	private static Font smallBold = new Font(Font.FontFamily.TIMES_ROMAN, 12,
			Font.BOLD);


    /**
     * @see HttpServlet#HttpServlet()
     */
    public PDFOrdonnance() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		manager = (Manager)request.getSession().getAttribute("manager");
		
		Integer id_ordonnance;
		if(manager != null && manager.isConnected()){
			if(request.getParameter("id_ordonnance") != null && !request.getParameter("id_ordonnance").equals("")){
				id_ordonnance = Integer.parseInt(request.getParameter("id_ordonnance"));
				Ordonnance ordonnance = manager.getServeurRmi().getOrdonnance(id_ordonnance);
				Medecin medecin = manager.getServeurRmi().getMedecin(ordonnance.getId_medecin());
				Patient patient = manager.getServeurRmi().getPatient(ordonnance.getNumero_securite_sociale_patient());
				
				response.setContentType("application/pdf");
				response.setHeader("Content-Disposition", "inline;filename=\""+ id_ordonnance +".pdf\"");
				
				BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
				
				Document document = new Document();
				
				try {
					PdfWriter.getInstance(document, bos);
				} catch (DocumentException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				generatePDFOrdonnance(document, ordonnance, medecin, patient);
				
				bos.flush();
			}else{
				ArrayList<String> messages = new ArrayList<String>();
				messages.add("Ordonnance invalide");
				manager.setMessages(messages);
				response.sendRedirect("ordonnance/lister_ordonnance.jsp");
			}
		}else{
			response.sendRedirect("connexion/connexion.jsp");
		}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	private void generatePDFOrdonnance(Document document, Ordonnance ordonnance, Medecin medecin, Patient patient){
		
		document.open();
		document.addTitle("Ordonnance du " +
				ordonnance.getDate_ordonnance() +
				" pour " + patient.getNom_patient() +
				" " + patient.getPrenom_patient());
		document.addSubject(patient.getNom_patient() +
				" " + patient.getPrenom_patient());
		document.addKeywords("Ordonnance");
		document.addAuthor(medecin.getNom_medecin() +
				" " + medecin.getPrenom_medecin());
		document.addCreator("Logiciel Cabinet Médical © Guillaume Dadoy, Emeric Tassel");
		
		Paragraph entete = new Paragraph("Dr. " + medecin.getNom_medecin() + " " + medecin.getPrenom_medecin() + "\n" + 
				medecin.getAdresse_medecin() + "\n" + 
				medecin.getCode_postal() + " " +
				medecin.getVille() + "\n"+
				"Numéro enregistrement ordre des médecins : "+medecin.getId_medecin() + "\n\n");
		
		String jour=ordonnance.getDate_ordonnance().substring(8,10);
		String mois=ordonnance.getDate_ordonnance().substring(5,7);
		String annee=ordonnance.getDate_ordonnance().substring(0,4);
		
		Paragraph date = new Paragraph("A Brest le "+jour+"/"+mois+"/"+annee);
		date.setAlignment(Element.ALIGN_RIGHT);
		
		jour=patient.getDate_naissance_patient().substring(8,10);
		mois=patient.getDate_naissance_patient().substring(5,7) ;
		annee=patient.getDate_naissance_patient().substring(0,4) ;
		Paragraph sujet = new Paragraph(patient.getNom_patient() + " " + 
				patient.getPrenom_patient() + "\n" + "Date de naissance : "+ 
				jour+"/"+mois+"/"+annee + "\n" +
				" Poids : " + patient.getPoids_patient() + " kg" +"\n\n", subFont);
		sujet.setAlignment(Element.ALIGN_CENTER);
		
		Paragraph description = new Paragraph(ordonnance.getDescription_ordonnance() + "\n\n");
		
		Paragraph liste_medicaments = new Paragraph();

		for (Medicament medicament : ordonnance.getListeMedicaments()) {
			liste_medicaments.add(medicament.getNom_medicament() + " " +
					medicament.getAdministration_medicament()+ " " +
					medicament.getQuantite_medicament() + " " +
					medicament.getFrequence_medicament() + "\n");
		}
		
		try {
			document.add(entete);
			document.add(date);
			document.add(sujet);
			document.add(description);
			document.add(liste_medicaments);
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		document.close();
		
	}

}